// 上传到七牛云方法（上传成功后存入数据库）
function uploadQiniu(filePath, key) {
  const qiniu = require('qiniu') // 引入模块
  const { accessKey, secretKey, bucket } = require('../config/qiniu') // key密钥文件
  const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)

  // bucket是存储空间名称
  const options = {
    scope: bucket
  }
  const putPolicy =  new qiniu.rs.PutPolicy(options)

  // 生成token 作为个人七牛云账号的识别标识
  const uploadToken = putPolicy.uploadToken(mac)
  const config = new qiniu.conf.Config()
  // 空间对应的机房 一定要按自己属区Zone对象
  config.zone = qiniu.zone.Zone_z2 // 华南
  config.useCdnDomain = true
  const localFile = filePath // 流文件
  const formUploader = new qiniu.form_up.FormUploader(config)
  const putExtra = new qiniu.form_up.PutExtra()
  // 文件上传promise
  return new Promise((resolve) => {
    // 以文件流的形式进行上传
    // uploadToken是token， key是上传到七牛后保存的文件名, localFile是流文件
    // putExtra是上传的文件参数，采用源码中的默认参数
    formUploader.putStream(uploadToken, key, localFile, putExtra, (respErr, respBody, respInfo) => {
      console.log('上传后回调参数', respErr, respBody, respInfo)
      if (respErr) {
        resolve(-1)
        return
      }
      if (respInfo.statusCode != 200) {
        resolve(-1)
      } else { // 上传成功后返回文件下载链接
        const { data } = respInfo
        resolve(getQiniuDownload(data.key))
      }
    })
  })
}
// 获取七牛云空间下载链接
function getQiniuDownload(key) {
  const qiniu = require('qiniu') // 引入模块
  const { accessKey, secretKey } = require('../config/qiniu') // key密钥文件
  const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
  const config = new qiniu.conf.Config()
  const bucketManager = new qiniu.rs.BucketManager(mac, config)
  const publicBucketDomain = 'http://files.jiangtao.ltd'
  // 公开空间访问链接
  return bucketManager.publicDownloadUrl(publicBucketDomain, key)
  
}

// 删除七牛云空间资源
function deleteQinniu(key) {
  const qiniu = require('qiniu') // 引入模块
  const { accessKey, secretKey, bucket } = require('../config/qiniu') // key密钥文件
  const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
  const config = new qiniu.conf.Config()
  config.zone = qiniu.zone.Zone_z2 // 华南
  const bucketManager = new qiniu.rs.BucketManager(mac, config)
  return new Promise(resolve => {
    bucketManager.delete(bucket, key, () => {
      resolve()
    })
  })
}
module.exports = {
  uploadQiniu,
  getQiniuDownload,
  deleteQinniu
}